package com.weiaibenpao.demo.chislim.ui;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.jaeger.library.StatusBarUtil;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.bean.EnrollResultBean;
import com.weiaibenpao.demo.chislim.bean.MatchDetailBean;
import com.weiaibenpao.demo.chislim.bean.UserBean;
import com.weiaibenpao.demo.chislim.hurui.activity.UserDetailActivity;
import com.weiaibenpao.demo.chislim.map.customview.CircleImageView;
import com.weiaibenpao.demo.chislim.model.MyModel;
import com.weiaibenpao.demo.chislim.sport.MarathonActivity;
import com.weiaibenpao.demo.chislim.sport.utils.Constant;
import com.weiaibenpao.demo.chislim.sport.utils.ShareUtils;
import com.weiaibenpao.demo.chislim.util.Default;
import com.weiaibenpao.demo.chislim.util.Utils;
import com.zhy.view.flowlayout.FlowLayout;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MatchDetailActivity extends AppCompatActivity {
    @BindView(R.id.content)
    ScrollView mContentView;
    @BindView(R.id.tv_share)
    TextView tvShare;
    @BindView(R.id.rl_reminder)
    RelativeLayout reminder;
    @BindView(R.id.tv_match_name)
    TextView tvTitle;
    @BindView(R.id.tv_district)
    TextView tvDistrict;
    @BindView(R.id.tv_district_distance)
    TextView tvDistrictDistance;
    @BindView(R.id.tv_avg_distance)
    TextView tvMemberAvgDistance;
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.tv_time_limit)
    TextView tvTimeLimit;
    @BindView(R.id.tv_enrollment)
    TextView tvEnrollment;
    @BindView(R.id.tv_remaining_name)
    TextView tvRemainingTime;
    @BindView(R.id.tv_status_btn)
    TextView tvStatusBtn;
    @BindView(R.id.enrolled_people_container)
    FlowLayout enrolledPeopleContainer;
    private static final String STARTER ="发起人";
    private static final String STATUS_IN_REVIEW = "待审核";
    private static final String STATUS_ENROLL = "加入";
    private static final String STATUS_PREPARE ="备赛中";
    private static final String STATUS_NOT_FULL = "未报满";
    private static final String STATUS_FULL = "已报满";
    private static final String STATUS_ENTER_MATCH = "去参赛";
    private static final String STATUS_END = "已结束";
    private static final String MSG_ALREADY_ENROLLED = "你已经报过名了";
    private static final String MSG_CANNOT_ENROLL = "参赛人数已满";
    public static final String MATCH_ID = "match_id";
    private ShareUtils shareUtils = new ShareUtils(this);
    private String mMatchName;
    private String mMatchDesc;
    private String mStatus;
    private String mShareUrl;
    private String mSelectName;
    private String mCityCode;
    private String mMatchShareId;
    private double mDistance;
    private long mStartTime;
    private long mEndTime;
    private int mEnrolledNum;
    private int mQuota;
    private int mMatchId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_match_detail);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this , getResources().getColor(R.color.blackbg ) , 0);
        initData();
    }

    public static void openActivity(Context context,int matchId){
        Intent intent = new Intent(context,MatchDetailActivity.class);
        intent.putExtra(MATCH_ID,matchId);
        context.startActivity(intent);
    }

    private void initData() {
        if(getIntent() != null){
            mMatchId = getIntent().getIntExtra(MATCH_ID,0);
        }
        if(Utils.isNetWorkConnected()) {
            requestData();
        }else {
            Toast.makeText(this, "亲，网络连了么？", Toast.LENGTH_LONG).show();
        }
    }

    private void requestData() {
        MyModel.getModel().getService().getMatchDetail(UserBean.getUserBean().userId,mMatchId).enqueue(new Callback<MatchDetailBean>() {
            @Override
            public void onResponse(Call<MatchDetailBean> call, Response<MatchDetailBean> response) {
                MatchDetailBean bean = response.body();
                if (bean != null && bean.getCode() == 0){
                    if(bean.getData() != null) {
                        showBaseInfo(bean.getData().getActivityMap());
                        showEnrolledPeople(bean.getData().getList());
                    }
                }else {
                    Toast.makeText(MatchDetailActivity.this,"数据请求失败",Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<MatchDetailBean> call, Throwable t) {
                Toast.makeText(MatchDetailActivity.this,"数据请求失败",Toast.LENGTH_LONG).show();
            }
        });
    }

    private void showBaseInfo(MatchDetailBean.DataBean.ActivityMapBean baseInfo){
        if(baseInfo != null){
            mContentView.setVisibility(View.VISIBLE);
            mMatchShareId = baseInfo.getActId();
            mMatchName = baseInfo.getMarathonTitle();
            mMatchDesc = baseInfo.getmContent();
            mShareUrl = baseInfo.getUrl();
            mEnrolledNum = baseInfo.getJoinNumber();
            mStartTime = Utils.dateStrToLong(baseInfo.getSportsStartTime(),"yyyy-MM-dd HH:mm");
            mEndTime = baseInfo.getSportsEndTime();
            mDistance = baseInfo.getDistance();
            mCityCode = baseInfo.getCode();
            if(!TextUtils.isEmpty(baseInfo.getAreaName())){
                mSelectName = baseInfo.getAreaName();
            }else if(!TextUtils.isEmpty(baseInfo.getCityName())){
                mSelectName = baseInfo.getCityName();
            }else {
                mSelectName = baseInfo.getProvinceName();
            }
            mQuota = baseInfo.getNumber();
            tvTitle.setText(mMatchName);
            tvDistrict.setText("挑战行政区: "+baseInfo.getProvinceName()+baseInfo.getCityName()+baseInfo.getAreaName());
            tvDistrictDistance.setText("行政区总里程: "+String.valueOf(baseInfo.getDistance())+"公里");
            tvMemberAvgDistance.setText("平均每人需跑里程: "+String.valueOf(baseInfo.getAvgDistance()+"公里"));
            tvStartTime.setText("开始时间: "+baseInfo.getSportsStartTime());
            tvTimeLimit.setText("完赛时间: "+baseInfo.getThroughTime());
            tvEnrollment.setText("报名人数: "+mEnrolledNum+getString(R.string.slash_sign)+mQuota);
            tvRemainingTime.setText(baseInfo.getRemainTime());
            updateStatusButton(baseInfo.getDmessage());
        }
    }

    private void updateStatusButton(String matchStatus) {
        mStatus = matchStatus;
        if(STATUS_ENROLL.equals(mStatus) || STATUS_ENTER_MATCH.equals(mStatus) || STATUS_PREPARE.equals(mStatus)){
            tvStatusBtn.setBackgroundResource(R.drawable.bg_round_corner_rect_blue);
            tvStatusBtn.setTextColor(getResources().getColor(R.color.white));
        }else {
            tvStatusBtn.setBackgroundResource(R.drawable.bg_round_corner_rect_gray);
            tvStatusBtn.setTextColor(getResources().getColor(R.color.black));
        }
        if(STATUS_ENROLL.equals(mStatus)){
            //以下功能也可以使用TextView的DrawableLeft属性实现
//                SpannableString spannableString = new SpannableString("加号"+mStatus);
//                Drawable drawable = getResources().getDrawable(R.drawable.ic_add);
//                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
//                ImageSpan imageSpan = new ImageSpan(drawable);
//                spannableString.setSpan(imageSpan, 0, 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
//                tvStatusBtn.setText(spannableString);

            tvStatusBtn.setText("+ "+matchStatus);
        }else {
            tvStatusBtn.setText(mStatus);
        }

        if(STATUS_PREPARE.equals(mStatus)){
            tvShare.setVisibility(View.VISIBLE);
        }
    }

    private void showEnrolledPeople(List<MatchDetailBean.DataBean.Participant>  enrolledList){
        if(enrolledList != null && enrolledList.size()>0){
            enrolledPeopleContainer.removeAllViews();
            int size = enrolledList.size();
            for(int i=0; i<size;i++){
                addParticipant(enrolledList.get(i));
            }
        }
    }

    private void addParticipant(final MatchDetailBean.DataBean.Participant participant) {
        View view = LayoutInflater.from(this).inflate(R.layout.item_people_enrolled,enrolledPeopleContainer,false);
        CircleImageView header = (CircleImageView) view.findViewById(R.id.header);
        loadImage(participant.getImage(),header);
        TextView tvStarter = (TextView) view.findViewById(R.id.tv_starter);
        TextView tvNickname = (TextView) view.findViewById(R.id.tv_nickname);
        TextView tvLevel = (TextView) view.findViewById(R.id.tv_level);
        tvLevel.setText("Lv"+participant.getMark());
        tvNickname.setText(participant.getName());
        if(TextUtils.equals(participant.getIdentity(),STARTER)){
            tvStarter.setVisibility(View.VISIBLE);
        }
        header.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UserDetailActivity.openActivity(MatchDetailActivity.this,participant.getUserId());
            }
        });
        ViewGroup.LayoutParams params = view.getLayoutParams();
        int width = (Utils.getScreenWidth()- enrolledPeopleContainer.getPaddingRight()- enrolledPeopleContainer.getPaddingLeft())/2;
        params.width = width;
        view.setLayoutParams(params);
        enrolledPeopleContainer.addView(view);
    }

    private void loadImage(String url, ImageView imageView) {
        if (imageView == null) {
            return;
        }
        if(isDestroyed()){
            return;
        }
        Glide
                .with(this)
                .load(url)
                .into(imageView);
    }



    @OnClick({R.id.iv_back,R.id.tv_share,R.id.iv_delete,R.id.tv_match_name,R.id.tv_status_btn})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_share:
                shareUtils.shareLink(Default.PRODUCT_URL+mShareUrl, mMatchName + mMatchShareId +getString(R.string.join_us),getString(R.string.default_share_content));
                break;
            case R.id.iv_delete:
                reminder.setVisibility(View.GONE);
                break;
            case R.id.tv_match_name:
                MatchDescriptionActivity.openActivity(this,mMatchName,mMatchDesc);
                break;
            case R.id.tv_status_btn:
                handleStatusButtonClick();
                break;

        }
    }

    private void handleStatusButtonClick(){
       if(STATUS_ENROLL.equals(mStatus)){
           showNotice();
       }else if(STATUS_ENTER_MATCH.equals(mStatus)){
           Intent intent = new Intent(this, MarathonActivity.class);
           intent.putExtra(Constant.MARATHON_TITLE,mMatchName);
           intent.putExtra(Constant.MARATHON_ID,String.valueOf(mMatchId));
           intent.putExtra(Constant.MARATHON_TYPE, MarathonActivity.TYPE_USER_LAUNCHED_MATCH);
           intent.putExtra(Constant.MATCH_START_TIME,String.valueOf(mStartTime));
           intent.putExtra(Constant.MATCH_END_TIME,String.valueOf(mEndTime));
           intent.putExtra(Constant.MARATHON_DISTANCE,String.valueOf(mDistance));
           intent.putExtra(Constant.CITY_CODE,mCityCode);
           intent.putExtra(Constant.SELECT_NAME,mSelectName);
           startActivity(intent);
           finish();
//           Log.e("handleClick","start time is "+mStartTime+"\nend time is "+mEndTime);
       }
    }

    private void showNotice(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("加入比赛");
        builder.setMessage("团队挑战赛是要靠跑友们一起完成的，“放鸽子”可能会被跑友吐槽!");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                enroll();
            }
        });
        builder.setCancelable(false);
        builder.show();
    }

    private void enroll(){
        // 点击加入后：修改StatusButton状态
        // 把自己信息封装为一个participant然后把自己头像插入到下方
        // 修改报名人数
        // 如果加入后状态为备赛中，那么右上方邀请展示出来
        // 或者点击加入后清空所有数据，重新请求详情接口，或者直接finish重新打开！
        MyModel.getModel().getService().joinMatch(UserBean.getUserBean().userId,mMatchId).enqueue(new Callback<EnrollResultBean>() {
            @Override
            public void onResponse(Call<EnrollResultBean> call, Response<EnrollResultBean> response) {
                EnrollResultBean bean = response.body();
                if (bean == null ){
                    Toast.makeText(MatchDetailActivity.this,"服务器错误，加入失败",Toast.LENGTH_LONG).show();
                    return;
                }
                if(bean.getCode() == 0){
                    if(bean.getData() != null && bean.getData().getActivityUser()!= null) {
                            updateStatusButton(bean.getData().getActivityUser().getDmessage());
                            MatchDetailBean.DataBean.Participant participant = new MatchDetailBean.DataBean.Participant();
                            participant.setName(UserBean.getUserBean().userName);
                            participant.setMark(UserBean.getUserBean().userMark);
                            participant.setImage(UserBean.getUserBean().userImage);
                            addParticipant(participant);
                            mEnrolledNum++;
                            tvEnrollment.setText("报名人数: "+mEnrolledNum+getString(R.string.slash_sign)+mQuota);
                    }
                }else if(bean.getCode() ==1){
                    Toast.makeText(MatchDetailActivity.this,MSG_ALREADY_ENROLLED,Toast.LENGTH_SHORT).show();
                }else if(bean.getCode() ==2){
                    Toast.makeText(MatchDetailActivity.this,MSG_CANNOT_ENROLL,Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<EnrollResultBean> call, Throwable t) {
                Toast.makeText(MatchDetailActivity.this,"加入失败",Toast.LENGTH_LONG).show();
            }
        });

    }

}
